package light.head.controller.inv;

import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import light.head.constant.Msg;
import light.head.constant.Parm;
import light.head.constant.Sys;
import light.head.constant.Url;
import light.head.dao.inv.InvBillConfingDAO;
import light.head.dao.inv.InvBusinessDAO;
import light.head.dao.inv.InvDepotDAO;
import light.head.dao.inv.InvOutStorageDAO;
import light.head.dao.inv.InvOutStorageDetailDAO;
import light.head.dao.inv.InvOutStorageItemDAO;
import light.head.dao.inv.InvReturnDetailDAO;
import light.head.dao.inv.InvReturnInfoDAO;
import light.head.dao.inv.InvReturnItemDAO;
import light.head.dao.inv.InvStorageDAO;
import light.head.dao.inv.InvStorageDetailDAO;
import light.head.dao.sys.OrganDAO;
import light.head.enm.RESULT;
import light.head.framework.base.SupporterController;
import light.head.framework.entity.PageBean;
import light.head.model.inv.InvOutStorage;
import light.head.model.inv.InvOutStorageDetail;
import light.head.model.inv.InvOutStorageItem;
import light.head.model.inv.InvReturnDetail;
import light.head.model.inv.InvReturnInfo;
import light.head.model.inv.InvReturnItem;
import light.head.model.inv.InvStorage;
import light.head.model.inv.InvStorageDetail;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
/**
 * 进货退货
 * @author yy
 *
 */
@Controller
@RequestMapping(value = Url.C_INVRETURNPURCHASE)
public class InvReturnPurchaseController extends SupporterController{
	private InvReturnInfoDAO infoDAO;
	private InvReturnItemDAO itemDAO;
	private InvReturnDetailDAO detailDAO;
	private InvStorageDAO isDAO;
	private InvStorageDetailDAO isdDAO;
	private InvOutStorageDAO iosDAO;
	private InvOutStorageItemDAO iosiDAO;
	private InvOutStorageDetailDAO iosdDAO;
	private OrganDAO organDAO;
	private InvBusinessDAO ibDAO;
	private InvBillConfingDAO ibcfDAO;
	private InvDepotDAO idDAO;
	  		
  	@RequestMapping(value = Url.INIT)
	public ModelAndView init(HttpServletRequest request,HttpServletResponse response) throws Exception{
		return new ModelAndView(Url.INVRETURNPURCHASE_INIT);
	}
	
	@RequestMapping(value = Url.QUERY)
	public ModelAndView query (HttpServletRequest request, HttpServletResponse response) throws Exception{
		PageBean pb = createPageBean(request);
		Map<String,String> map = createQueryMapByParmName(request, Parm.DELETED,Parm.TIME1,Parm.TIME2,Parm.DNAME,Parm.DN,Parm.CN);
			if (infoDAO.findByMap(Sys.B_ONE,organDAO.getSonCodeList(cu_organCode(request)), map, pb) == RESULT.SUCCESS) {
				InvReturnInfo isi =null;
				for (Object o : pb.getResultList()) {
					isi = (InvReturnInfo) o;
					isi.setItemList(itemDAO.findByRc(isi.getCode()));
				}
				request.setAttribute(Parm.PAGE_BEAN, pb);
			}
			return new ModelAndView(Url.INVRETURNPURCHASE_LIST);
		}
	
	@RequestMapping(value = Url.EDIT)
	public ModelAndView edit(HttpServletRequest request, HttpServletResponse response){
		String code = request.getParameter(Parm.CODE);
		if (null != code) {
			InvReturnInfo is = infoDAO.get(Integer.parseInt(code));
			List<InvReturnItem> itemList = itemDAO.findByRc(is.getCode());
			is.setItemList(itemList);
			request.setAttribute(Parm.PURCHASE, is);
		} 
		return new ModelAndView(Url.INVRETURNPURCHASE_EDIT);
	}
	@RequestMapping(value = Url.DETAIL)
	public ModelAndView detail(HttpServletRequest request, HttpServletResponse response){
		String code = request.getParameter(Parm.CODE);
		if (null != code) {
			InvReturnInfo iis = infoDAO.get(Integer.parseInt(code));
			List<InvReturnItem> itemList = itemDAO.findByRc(iis.getCode());
			iis.setItemList(itemList);
			for (InvReturnItem item : itemList) {
				List<InvReturnDetail> detailList = detailDAO.findByRic(item.getCode());
				item.setDetailList(detailList);
			}
			request.setAttribute(Parm.PURCHASE, iis);
		} 
		return new ModelAndView(Url.INVRETURNPURCHASE_DETAIL);
	}
	
	//进货退货
	@Transactional
	@RequestMapping(value = Url.SAVE)
	public void save(InvReturnInfo iri, HttpServletRequest request, HttpServletResponse response) throws Exception{
		RESULT result = RESULT.ERROR;
		List<InvReturnItem> itemList = iri.getItemList();			// 提交上来的数组
		iri.setDn(ibcfDAO.createBCode(organDAO.getRoot(cu_organCode(request)).getCode(), Sys.B_ELEVEN));
		iri.setType(Sys.B_ONE);
		iri.setCt(new Date());
		iri.setDeleted(false);
		iri.setCu(cu_code(request));
		iri.setOc(cu_organCode(request));
		result = infoDAO.add(iri); 	// 零售记录s
		//保存出库信息
		InvOutStorage ios = new InvOutStorage();
		ios.setDn(ibcfDAO.createBCode(organDAO.getRoot(cu_organCode(request)).getCode(), Sys.B_FOUR));
		ios.setCt(new Date());
		ios.setCu(cu_code(request));
		ios.setDeleted(false);
		ios.setBc(iri.getBc());
		ios.setOc(cu_organCode(request));
		ios.setType(Sys.B_FOUR);
		result = iosDAO.add(ios);
		// 保存
		for (InvReturnItem item : itemList) {
			if (item != null && item.getCc() != null && item.getCount() != null){
				// 保存退货明细
				item.setRc(iri.getCode());
				item.setDeleted(false);
				result = itemDAO.add(item);
				//保存出库明细
				InvOutStorageItem iosi = new InvOutStorageItem();
				iosi.setCc(item.getCc());
				iosi.setDc(item.getDc());
				iosi.setDeleted(false);
				iosi.setIosc(ios.getCode());
				iosi.setNumber(item.getCount());
				result = iosiDAO.add(iosi);
				// 保存库存
				Integer oc = organDAO.getRoot(cu_organCode(request)).getCode();
				List<InvStorage> dbList = isDAO.findByCcDc(item.getCc(),item.getDc(), organDAO.getSonCodeList(cu_organCode(request)));
				// 保存出库记录
				String serial = isdDAO.findByCcOc(item.getCc(), organDAO.getSonCodeList(oc));
				if (item.getSnc().intValue() == 2 && serial != null) {
					InvOutStorageDetail iosd = new InvOutStorageDetail();
					iosd.setDeleted(false);
					iosd.setIosic(iosi.getCode());
					iosd.setSerial(serial);
					result = iosdDAO.add(iosd);
					InvReturnDetail ird = new InvReturnDetail();
					ird.setDeleted(false);
					ird.setRic(item.getCode());
					ird.setSerial(serial);
					result = detailDAO.add(ird);
				}
				if (null != dbList && dbList.size() > 0) {
					if (dbList.get(0).getCount().intValue() <= 0 ) {
						print(response, Msg.EXISTS);
						return;
					}if (dbList.get(0).getCount().intValue() < item.getCount().intValue()) {
						print(response, Msg.NOT_FIND);
						return;
					}
					dbList.get(0).setCount(dbList.get(0).getCount() - item.getCount());
					result = isDAO.upd(dbList.get(0));
					if (item.getSnc().intValue() == 3 || (item.getSnc().intValue() == 2 && serial == null)) {
						//保存退货串号
						if (item.getDetailList() != null && item.getDetailList().size() > 0) {
							for(InvReturnDetail ird : item.getDetailList()){
								if (ird != null && ird.getSerial() != null) {
									ird.setDeleted(false);
									ird.setRic(item.getCode());
									result = detailDAO.add(ird);	
									// 删除库存串号
									if (result == RESULT.SUCCESS){
										List<InvStorageDetail> isdList = isdDAO.findByOc(ird.getSerial(), organDAO.getSonCodeList(oc));
										if (null != isdList && isdList.size() > 0){
											result = isdDAO.del(isdList.get(0));	
										}								
									}
									//保存出库串号
									InvOutStorageDetail iosd = new InvOutStorageDetail();
									iosd.setDeleted(false);
									iosd.setIosic(iosi.getCode());
									iosd.setSerial(ird.getSerial());
									result = iosdDAO.add(iosd);
								}
							}
						}
					}
				} else {
					print(response, Msg.ERROR);
					return;
				}
			}
		}
		print(response, Msg.SUCCESS);
	}
	
	  
	/**
	 * 查询库存商品
	 */
	@RequestMapping(Url.S_INIT)
	public ModelAndView sInit(HttpServletRequest request, HttpServletResponse response) throws Exception {
		request.setAttribute(Parm.INDEX, request.getParameter(Parm.INDEX));
		System.out.println(request.getParameter(Parm.INDEX));
		return new ModelAndView(Url.INVRETURNPURCHASE_S_INIT);
	}
	
	@RequestMapping(Url.S_LIST)
	public ModelAndView sList(HttpServletRequest request, HttpServletResponse response) throws Exception {
		PageBean pageBean = createPageBean(request);
		Map<String, String> map = createQueryMapByParmName(request, Parm.OC, Parm.NAME,Parm.FAST);
		if (RESULT.SUCCESS == isDAO.findByMap_1(organDAO.getSonCodeList(cu_organCode(request)), map,pageBean)) {
			request.setAttribute(Parm.PAGE_BEAN, pageBean);
		}
		return new ModelAndView(Url.INVRETURNPURCHASE_S_LIST);
	}
  
	/**
	 * 查询仓库
	 */
	@RequestMapping(Url.AID_INIT_1)
	public ModelAndView aidInit1(HttpServletRequest request, HttpServletResponse response) throws Exception {
		request.setAttribute(Parm.INDEX, request.getParameter(Parm.INDEX));
		System.out.println(request.getParameter(Parm.INDEX));
		return new ModelAndView(Url.INVRETURNPURCHASE_AID_INIT1);
	}
	
	@RequestMapping(Url.AID_LIST_1)
	public ModelAndView aidList1(HttpServletRequest request, HttpServletResponse response) throws Exception {
		PageBean pageBean = createPageBean(request);
		Map<String, String> map = createQueryMapByParmName(request, Parm.OC, Parm.NAME);
		if (RESULT.SUCCESS == idDAO.findByMap(organDAO.getSonCodeList(cu_organCode(request)), map,pageBean)) {
			request.setAttribute(Parm.PAGE_BEAN, pageBean);
		}
		return new ModelAndView(Url.INVRETURNPURCHASE_AID_LIST1);
	}
	/**
	 * 查询供应商
	 */
	@RequestMapping(Url.AID_INIT_2)
	public ModelAndView aidInit2(HttpServletRequest request, HttpServletResponse response) throws Exception {
		return new ModelAndView(Url.INVRETURNPURCHASE_AID_INIT2);
	}
	
	@RequestMapping(Url.AID_LIST_2)
	public ModelAndView aidList2(HttpServletRequest request, HttpServletResponse response) throws Exception {
		PageBean pageBean = createPageBean(request);
		Map<String, String> map = createQueryMapByParmName(request, Parm.OC, Parm.NAME);
		Integer oc = organDAO.getRoot(cu_organCode(request)).getCode();
		if (RESULT.SUCCESS == ibDAO.findByMap(oc, map,pageBean)) {
			request.setAttribute(Parm.PAGE_BEAN, pageBean);
		}
		return new ModelAndView(Url.INVRETURNPURCHASE_AID_LIST2);
	}
	//判断序列号是否是该库存下的商品所属
	@RequestMapping(value = Url.VERIFY2)
	public void serial2(HttpServletRequest request, HttpServletResponse response)throws Exception {
		String serial = request.getParameter("serial");
		String cc = request.getParameter("cc");
		String dc = request.getParameter("dc");
		List<InvStorageDetail> detailList = isdDAO.findBySerialCcDc(serial,Integer.parseInt(cc),Integer.parseInt(dc));
		if (detailList != null && detailList.size() > 0) {
			print(response, Msg.SUCCESS);
			
		} else {
			print(response, Msg.ERROR);
			return;
		}
	}
	
	// 用序列号到库存查询出对应的商品信息
	@RequestMapping(value = Url.VERIFY)
	public void loadCommodity(HttpServletRequest request, HttpServletResponse response)throws Exception {
		String serial = request.getParameter(Parm.SERIAL);
		Object obj = isdDAO.findBySerial(serial, organDAO.getSonCodeList(cu_organCode(request)));
		
		if (null != obj) {
			Object[] comm = (Object[]) obj;
			Byte snc = null != comm[2] ? (Byte) comm[2] : null;
			String name = "";
			if (null !=  snc && snc.byteValue() == 1)
				name = "不需要序列号";
			else if (null !=  snc && snc.byteValue() == 2)
				name = "同类序列号";
			else
				name = "唯一序列号";
					
					
			StringBuffer result = new StringBuffer("{");
			
			result.append("\"cc\":\"" + comm[0] +"\",");
			result.append("\"cname\":\"" + comm[1] +"\",");
			result.append("\"snc\":\"" + comm[2] +"\",");
			result.append("\"s\":\"" + name +"\",");
			result.append("\"price\":\"" + comm[3] +"\",");
			result.append("\"serial\":\"" + comm[4] +"\",");
			result.append("\"dc\":\"" + comm[5] +"\",");
			result.append("\"dname\":\"" + comm[6] +"\"");
			result.append("}");
			print(response, result.toString());
		} else {
			return;
		}
	}
	
	
	
	@Autowired
	public void setInfoDAO(InvReturnInfoDAO infoDAO) {
		this.infoDAO = infoDAO;
	}
  	@Autowired
	public void setItemDAO(InvReturnItemDAO itemDAO) {
		this.itemDAO = itemDAO;
	}
  	@Autowired
	public void setDetailDAO(InvReturnDetailDAO detailDAO) {
		this.detailDAO = detailDAO;
	}
  	@Autowired
	public void setOrganDAO(OrganDAO organDAO) {
		this.organDAO = organDAO;
	}
  	@Autowired
	public void setIsDAO(InvStorageDAO isDAO) {
		this.isDAO = isDAO;
	}
  	@Autowired
	public void setIsdDAO(InvStorageDetailDAO isdDAO) {
		this.isdDAO = isdDAO;
	}
  	@Autowired
	public void setIbDAO(InvBusinessDAO ibDAO) {
		this.ibDAO = ibDAO;
	}
  	@Autowired
	public void setIbcfDAO(InvBillConfingDAO ibcfDAO) {
		this.ibcfDAO = ibcfDAO;
	}
  	@Autowired
	public void setIdDAO(InvDepotDAO idDAO) {
		this.idDAO = idDAO;
	}
  	@Autowired
	public void setIosDAO(InvOutStorageDAO iosDAO) {
		this.iosDAO = iosDAO;
	}
  	@Autowired
	public void setIosiDAO(InvOutStorageItemDAO iosiDAO) {
		this.iosiDAO = iosiDAO;
	}
  	@Autowired
	public void setIosdDAO(InvOutStorageDetailDAO iosdDAO) {
		this.iosdDAO = iosdDAO;
	}
  	
}
